package com.lw.client;

import com.lw.common.Message;
import com.lw.common.MessageType;

import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 文件传输服务
 */
public class FileClientService {

    private int limitLength = 1024*1024*30;//30M

    /**
     * 发送文件给某人
     * @param src  源文件路径
     * @param senderId
     * @param receiveId
     */
    public void sendFileToOne(String src,String senderId,String receiveId) throws IOException {
        File file = new File(src);

        Socket socket = ManageClientConnectServerThread.getClientConnectServerThread(senderId).getSocket();

        Message message = new Message();
        message.setReceiver(receiveId);
        message.setSender(senderId);
        message.setSrc(src);
        message.setFileName(file.getName());

//        if(file.length()<limitLength){
//            this.sendSmallFile(message,socket);
//        }else{
//            this.sendBigFile(message,socket);
//        }
        this.sendBigFile(message,socket);

        System.out.println("文件发送完毕");
    }

    /**
     * 发送大文件
     */
    private void sendBigFile(Message message,Socket socket) throws IOException {
        message.setMsgType(MessageType.MESSAGE_BIG_FILE_MES);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(message.getSrc()));
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen=bis.read(buf))!=-1){//读取文件
            if(readLen!=buf.length){
                byte[] data = new byte[readLen];
                System.arraycopy(buf,0,data,0,readLen);
                message.setFileBytes(data);
            }else{
                message.setFileBytes(buf);
            }

            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(message);
        }
        bis.close();

        //文件发送完毕
        message.setSendFileOver(true);
        ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
        outputStream.writeObject(message);

    }

    /**
     * 发送小文件
     */
    private void sendSmallFile(Message message,Socket socket) throws IOException {
        message.setMsgType(MessageType.MESSAGE_FILE_MES);
        //如果文件比较小，则可以不使用上述方法，直接将文件全部读出来成字节数组即可
        byte[] fileBytes = Files.readAllBytes(Paths.get(message.getSrc()));
        message.setFileBytes(fileBytes);
        message.setSendFileOver(true);

        //发送文件信息
        ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
        outputStream.writeObject(message);
    }
}
